import hashlib

from flask import Blueprint, render_template, request, session

from utils.database_util import query_data

user_center = Blueprint('user_center', __name__)

@user_center.route('/center')
def center():
    return render_template('user_center.html')

@user_center.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        password = hashlib.md5(password.encode()).hexdigest()
        sql = "select * from users where username = '%s' and password = '%s'" % (username, password)
        result = query_data(sql)
        if len(result) == 0:
            return render_template("login.html")
        else:
            session['username'] = username
            session['islogin'] = 'true'
            session['userid'] = result[0].get('userid')
            session['nickname'] = result[0].get('nickname')
            session['role'] = result[0].get('role')
        return render_template('home.html')

    else:
        return render_template('login.html')

@user_center.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        print(username)
        password = request.form.get('password')
        password = hashlib.md5(password.encode()).hexdigest()
        print('密码是:',password)
        nickname = request.form.get('nickname')
        print(nickname)
        sql = "insert into users (username, password, nickname) values ('%s', '%s', '%s')" % (username, password, nickname)
        print(sql)
        result = query_data(sql)
        login()
        return render_template('home.html')
    else:
        return render_template('register.html')

@user_center.route('/logout')
def logout():
    session.clear()
    return render_template('home.html')


@user_center.route('/mine')
def mine():
    return render_template('mine.html')

@user_center.route('/my_love')
def my_love():
    return render_template('my_favorite.html')

@user_center.route('/my_comments')
def my_comments():
    return render_template('comments.html')

@user_center.route('/my_test')
def my_test():
    return render_template('my_test.html')

@user_center.route('/credit')
def credit():
    return render_template('credit.html')

@user_center.route('/myself')
def myself():
    return render_template('myself.html')
